package com.zlq.javaWeb3.controller;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

import static java.lang.Math.*;

@WebServlet(urlPatterns = "/makeController")
public class MakeController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        char[] codes = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
                'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
                'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', };
        int num = 4;
        String s = randomCode(4, codes);
        req.getSession().setAttribute("vs",s);
        BufferedImage bi = draw(80, 40, 3, resp, s);

        // 设置图像缓存为no-cache。
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);
        resp.setContentType("image/jpeg");
        //应答输出流，图片是响应的方式出去的，在页面展示
        ServletOutputStream out = resp.getOutputStream();
        ImageIO.write(bi, "jpg",out);
        out.close();

    }
    private String randomCode(int num,char[] codes){
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < num; i++) {
            //System.out.println(random());
            sb.append(codes[(int) (random() * codes.length)]);
        }
        String s = sb.toString();
        System.out.println(s);
        return s;
    }
    private BufferedImage draw(int width,int height,int type,HttpServletResponse resp,String s){
        BufferedImage bi = new BufferedImage(width,height,type);
        //画笔
        Graphics2D g = bi.createGraphics();
        //给画笔沾色
        g.setColor(Color.orange);
        //填充背景
        g.fillRect(0,0,width,height);
        g.setColor(Color.BLACK);
        //画边框
        g.drawRect(0,0,width-1, height-1);
        g.setFont(new Font("黑体",10,20));
        g.setColor(Color.black);
        g.drawString(s,20,25);
        g.setColor(Color.CYAN);
        //加干扰线
        for (int i = 0; i < 100; i++) {
            int x = (int) (random()*width);
            int y = (int) (random()*height);
            int x1 = (int) (random()*10);
            int y1 = (int) (random()*10);
            g.drawLine(x, y, x+x1,y+y1);
        }
        return bi;
    }
}
